import pymysql


class DBUtils:
    def __init__(self,host,user,passwd,database,port=3306,charset='utf8'):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.database = database
        self.charset = charset

    def sql_cru(self,sql,data=None):
        db = pymysql.connect(
            host=self.host,
            user=self.user,
            passwd=self.passwd,
            database=self.database,
            charset=self.charset,
            port=self.port,
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,data)
                db.commit()
                print("数据库操作成功！")
        except Exception as e:
            print("数据库操作失败！",e)
        finally:
            db.close()


    def sql_u(self,sql):
        db = pymysql.connect(
            host=self.host,
            user=self.user,
            passwd=self.passwd,
            database=self.database,
            charset=self.charset,
            port=self.port,
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql)
                db.commit()
                print("数据库操作成功！")
        except Exception as e:
            print("数据库操作失败！", e)
        finally:
            db.close()


    def sql_d(self,sql):
        db = pymysql.connect(
            host=self.host,
            user=self.user,
            passwd=self.passwd,
            database=self.database,
            charset=self.charset,
            port=self.port,
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql)
                data = cursor.fetchall()
                return data
        except Exception as e:
            return False
        finally:
            db.close()


# if __name__ == '__main__':
#     db = DBUtils(
#         host="localhost",
#         user="root",
#         passwd="@WJN+000**",
#         database="hrjt",
#     )

    # 循环插入
    # for i in range(10):
    #     name = input("姓名：")
    #     sex = input("性别：")
    #     age = int(input("年龄："))
    #     high = float(input("身高："))
    #
    #     data = (name,sex,age,high)
    #     sql = "insert into person(name,sex,age,high) values(%s,%s,%s,%s)"
    #     db.sql_cru(sql,data)

    # # 全量查询
    # sql = "select * from person"
    # db.sql_d(sql)

